<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="../css/bootstrap.min.css">
</head>
<body>
       <!-- 给一个容器 -->
       <div class="container">
        <div class="row text-center" >
            <h1>学生信息管理系统</h1>
            <hr>

            <a href="/index.html" class="btn btn-success">首页</a>
            <a href="/add.html" class="btn btn-warning">添加</a>

            <br>
            <br>
        </div>

        <!-- col-md-8 中等屏幕的8  12 -->
       <!-- <form action="/add" method="post" role="form" class="col-md-5"> -->

        <div class="row">
            <div class="form-group col-md-5">
                <label for="username">姓名</label>
                <input type="text" name="username" id="username" class="form-control">
            </div>
        </div>

        <div class="row">
            <div class="form-group col-md-5">
                <label for="sex">性别</label>
                <input type="text" name="sex" id="sex" class="form-control">
            </div>
        </div>

        <div class="row">
            <div class="form-group col-md-5">
                <label for="age">年龄</label>
                <input type="text" name="age" id="age" class="form-control">
            </div>
        </div>
        <p class="tip"></p>

        <div class="row">

            <div class="text-center col-md-5">
                <button type="submit" class="btn btn-success submit">提交</button>
                <button type="reset" class="btn btn-danger">重置</button>
            </div>
        </div>
       <!-- </form> -->

    </div>
    <script>
        let btn = document.querySelector(".submit");
        btn.onclick=()=>{
            console.log(username,username.value,sex.value,age.value)
            let xhr = new XMLHttpRequest();
            xhr.open("post","/add",true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            xhr.send(`name=${username.value}&sex=${sex.value}&age=${age.value}`); 
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        //获取span标签
                        let tip = document.querySelector(".tip");
                        // window.location="/index.html"
                        console.log(xhr.response);
                        let data = JSON.parse(xhr.response);
                        if(data.code==200){
                            console.log(xhr.response)
                            window.location="/"+data.mag
                            return
                        }
                        tip.innerHTML = data.mag;
                    }
                }
            }
        }
    </script>
</body>
</html>
